package com.ash.android_adk_demo;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.ash.android_adk_demo.ParentAdapter;
import com.ash.android_adk_demo.databinding.ActivityMainForJavaBinding;
import com.ash.base.AppConfig;
import com.ash.base.bean.BaseSolution;
import com.ash.base.bean.Cure;
import com.ash.base.bean.HcResult;
import com.ash.base.bean.Schemes;
import com.ash.base.bean.SecureSolution;
import com.ash.base.bean.Solution;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hc.hcsdk.HCSDK;
import com.hc.player.common.IPlayerListener;
import com.hc.player.common.PlayerEventBus;
import com.hc.player.player.ASMRPlayer;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RequiresApi(api = Build.VERSION_CODES.O)
public class MainActivityForJava extends ComponentActivity implements View.OnClickListener {

    private final String TAG = "MainActivityForJava";
    private HCSDK hcSdk;
    private final String channelCode = "yshrkz";
    private final String userId = "c9eea403-3f5f-11ef-9c91-00163e3195fd";
    private ASMRPlayer player;
    private ActivityMainForJavaBinding binding;

    private final IPlayerListener playerListener = new IPlayerListener() {
        @Override
        public void onCacheAllDone(Exception exception) {
            Log.e(TAG, "onAllDone");
            player.play();
        }

        @Override
        public void onCachePreDownloadDone() {
            Log.e(TAG, "onPreDownloadDone");
            player.play();
        }

        @Override
        public void onCacheError(Exception e) {
            Log.e(TAG, "onError");
        }

        @Override
        public void onClearCache() {
            Log.e(TAG, "onClearCache");
        }

        @Override
        public void onTick(long tick) {
            Log.e(TAG, "onTick");
        }

        @Override
        public void onFinished() {
            Log.e(TAG, "onFinished");
        }

        @Override
        public void onPlay() {
            Log.e(TAG, "onPlay");
        }

        @Override
        public void onPause() {
            Log.e(TAG, "onPause");
        }

        @Override
        public void onPlayError(Exception e) {
            Log.e(TAG, "onPlayError");
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onTrimMemory(int level) {
        Log.e(TAG, "onTrimMemory: ");
        super.onTrimMemory(level);
    }

    private void bindClick() {
        binding.rvParentListClass.setLayoutManager(new LinearLayoutManager(this));
        binding.btnLoginClass.setOnClickListener(this);
        binding.btnStopClass.setOnClickListener(this);
        binding.btnQueryCuresClass.setOnClickListener(this);
        binding.btnZbjsClass.setOnClickListener(this);
        binding.btnScheduleClass.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate: ");
        try {
            binding = ActivityMainForJavaBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            hcSdk = HCSDK.getShared(this);
            hcSdk.initialize(
                    channelCode, // 渠道码
                    AppConfig.INSTANCE.getPathPrefix(), // 产品工程，默认填此即可
                    "http://47.100.120.192",  // host，正式使用时可不填
                    true
            );

            player = new ASMRPlayer(getApplicationContext());


            bindClick();
            PlayerEventBus.getInstance().addLisenter(playerListener);
        } catch (Exception e) {
            Log.d(TAG, "onCreate" + e.getMessage());
        }
    }

    private void playCure(Schemes scheme, int duration) {
        Log.d(TAG, "solution:======播放====== " + scheme.getId() + " " + duration);
        try {
            hcSdk.getProvider().getSolutionAsync(String.valueOf(scheme.getId()), duration, scheme.getSchemeName()).thenAccept((result) -> {
                if (result instanceof HcResult.Success) {
                    BaseSolution baseSolution = ((HcResult.Success<BaseSolution>) result).getData();
                    if (baseSolution instanceof SecureSolution) {
                        SecureSolution secureSolution = (SecureSolution) baseSolution;
                        // 播放预备
                        Log.d(TAG, "在线播放prepare");
                        player.prepare(secureSolution.getAudioPlans(), (long) duration, true);
                    } else if (baseSolution instanceof Solution) {
                        Log.d(TAG, "离线播放prepare");
                        Solution solution = (Solution) baseSolution;
                        player.prepare(solution);
                    }
                } else if (result instanceof HcResult.Error) {
                    Log.e(TAG, "onError: " + ((HcResult.Error) result).getMess());
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "playCure: " + e.getMessage());
        }
    }

    private void toast(String msg) {
        runOnUiThread(() -> Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_stop_class) {
            player.stop();
        } else if (id == R.id.btn_login_class) {
            try {
                hcSdk.loginAsync(userId).thenAccept(result -> {
                    runOnUiThread(() -> {
                        binding.tvStatusClass.setText("已登录");
                    });
                });
            } catch (Exception e) {
                Log.e(TAG, "登录失败");
            }
        } else if (id == R.id.btn_query_cures_class) {
            try {
                CompletableFuture future = hcSdk.getProvider().getSchemeListAsync();
                future.thenAccept(result -> {

                    if (result instanceof HcResult.Success) {
//                    "请求列表：${result.data}".logd()
                        Log.d(TAG, "onClick: 获取数据List");
                        @Nullable
                        List<Cure> cures = ((HcResult.Success<List<Cure>>) result).getData();
                        if (cures == null) {

                        } else {
                            ParentAdapter adapter = new ParentAdapter(cures, null);
                            Log.d(TAG, "获取成功：" + cures.size() + cures.get(0).toString());
                            adapter.setOnItemClickLitener(new ParentAdapter.OnItemClickLitener() {
                                                              @Override
                                                              public void onItemClick(@NonNull View view, @NonNull Schemes scheme) {
                                                                  Log.d(TAG, "onItemClick: 播放方案：" + scheme.getId() + scheme.getSchemeName());
                                                                  String jsonStr = scheme.getExtConfigJson();
                                                                  JsonObject jsonObject = new Gson().fromJson(jsonStr, JsonObject.class);
                                                                  JsonArray jsList = jsonObject.getAsJsonArray("durations");
//                                            示例播放第一个时长
                                                                  int _duration = Integer.parseInt(jsList.get(0).toString());
                                                                  playCure(scheme, _duration);
                                                              }
                                                          }
                            );
                            runOnUiThread(() -> {
                                Log.d(TAG, "设置适配器： " + (adapter == null));
                                binding.rvParentListClass.setAdapter(adapter);
                            });

                        }
                    } else if (result instanceof HcResult.Error) {
//                    result.mess.logd()
                        Log.e(TAG, "onClick: " + ((HcResult.Error) result).getMess());
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "btn_query_cures_class: " + e.getMessage());
            }

        }else if (id == R.id.btn_zbjs_class){
            startActivity(
                    new Intent(this, PsyActivity.class));
        }else if (id == R.id.btn_schedule_class){
            startActivity(
                    new Intent(this, ScheduleActivity.class));
        }
    }
}